<?php

// no direct access
defined ( '_JEXEC' ) or die ( 'Restricted access' );

require_once JPATH_SITE . '/components/com_content/helpers/route.php';
JModel::addIncludePath ( JPATH_SITE . '/components/com_content/models' );
if (file_exists ( JPATH_SITE . DS . 'components' . DS . 'com_k2' . DS . 'helpers' . DS . 'route.php' )) {
require_once (JPATH_SITE . DS . 'components' . DS . 'com_k2' . DS . 'helpers' . DS . 'route.php');
}
if (file_exists ( JPATH_SITE . DS . 'components' . DS . 'com_k2' . DS . 'helpers' . DS . 'utilities.php' )) {
require_once (JPATH_SITE . DS . 'components' . DS . 'com_k2' . DS . 'helpers' . DS . 'utilities.php');
}

class modOLshowNewsHelper {
var $conditons = '';
var $order = 'ordering';
var $limit = '';	
var $mode = '';
var $iwidth = 0;
var $iheight = 0;	
var $_html = array ();	
var $_img = array ();
function getList($params) {
$rows = array ();

// check cache was endable ?
if ($params->get ( 'enable_cache', 1 )) {
$cache = & JFactory::getCache ();
$cache->setCaching ( true );
$cache->setLifeTime ( $params->get ( 'cache_time', 30 ) * 60 );
$rows = $cache->get ( array ($this, 'getArticles' ), array ($params ) );
} else {
$rows = $this->getArticles ( $params );
}

return $rows;
}

function getArticles($params) {
$order = $params->get ( 'sort_order_field', 'created' );
if (trim ( $order ) != "rand") {
$this->setOrder ( "a." . $order, $params->get ( 'sort_order', 'DESC' ) );
} else {
$this->setOrder ( "RAND()", "" );
}
$this->setLimit ( $params->get ( 'max_items', 5 ) );
$rows = $this->getListArticles ( $params );

return $rows;
}

/**
* get list articles follow setting configuration.
*
* @param JParameter $param
* @return array 
*/
function getListArticles($params, $showcontentfrontpage = false) {
// Get the dbo
$db = JFactory::getDbo ();

// Get an instance of the generic articles model
$model = JModel::getInstance ( 'Articles', 'ContentModel', array ('ignore_request' => true ) );

// Set application parameters in model
$appParams = JFactory::getApplication ()->getParams ();
$model->setState ( 'params', $appParams );

// Set the filters based on the module params
$model->setState ( 'list.start', 0 );
$catid = $params->get ( 'catid', '' );
if (! empty ( $catid ) && $this->limit > 0) {
$model->setState ( 'list.limit', $this->limit );
}

$model->setState ( 'filter.published', 1 );

// Access filter
$access = ! JComponentHelper::getParams ( 'com_content' )->get ( 'show_noauth' );
$authorised = JAccess::getAuthorisedViewLevels ( JFactory::getUser ()->get ( 'id' ) );
$model->setState ( 'filter.access', $access );

// Category filter
if (! empty ( $catid )) {
$model->setState ( 'filter.category_id', $catid );
}
// Set ordering
$order_map = array ('m_dsc' => 'a.modified DESC, a.created', 'mc_dsc' => 'CASE WHEN (a.modified = ' . $db->quote ( $db->getNullDate () ) . ') THEN a.created ELSE a.modified END', 'c_dsc' => 'a.created', 'p_dsc' => 'a.publish_up' );
$ordering = JArrayHelper::getValue ( $order_map, 'a.ordering', 'a.publish_up' );
//$dir = 'DESC';
$model->setState ( 'list.ordering', $this->order );
$model->setState ( 'list.direction', $this->mode );

$items = $model->getItems ( true );
if (empty ( $items ))
return;
foreach ( $items as &$item ) {
$item->slug = $item->id . ':' . $item->alias;
$item->catslug = $item->catid . ':' . $item->category_alias;

if ($access || in_array ( $item->access, $authorised )) {
// We know that user has the privilege to view the article
$item->link = JRoute::_ ( ContentHelperRoute::getArticleRoute ( $item->slug, $item->catslug ) );
} else {
$item->link = JRoute::_ ( 'index.php?option=com_user&view=login' );
}

$item->introtext = JHtml::_ ( 'content.prepare', $item->introtext );
}

return $items;
}

function getIds($options) {
if (! is_array ( $options )) {
return ( int ) $options;
} else {
return "'" . implode ( "','", $options ) . "'";
}
}

function setOrder($order, $mode) {
$this->order = $order;
$this->mode = $mode;
return $this;
}

function setLimit($limit) {
$this->limit = $limit;
return $this;
}

function trimStringOld($title, $max = 60) {

if (strlen ( $title ) > $max) {
return substr ( $title, 0, $max ) . '...';
}
return $title;
}

function getLink($item) {
if (! isset ( $item->slug ) && ! isset ( $item->catslug ) && isset ( $item->categoryalias )) {
return urldecode ( JRoute::_ ( K2HelperRoute::getItemRoute ( $item->id . ':' . urlencode ( $item->alias ), $item->catid . ':' . urlencode ( $item->categoryalias ) ) ) );
} else {
return JRoute::_ ( ContentHelperRoute::getArticleRoute ( $item->slug, $item->catslug ) );
}

}

/**
*
*
*/
function replaceImage(&$row, $autoresize, $maxchars, $width = 0, $height = 0) {
global $database, $_MAMBOTS, $current_charset;
$image = "";
//Get image
$regex = "/\<img.*\/\>/";
preg_match ( $regex, $row->introtext, $matches );
$row->text = preg_replace ( $regex, '', $row->introtext );

$row->introtext = preg_replace ( $regex, '', $row->introtext );
$row->introtext = trim ( $row->introtext );

$image = count ( $matches ) ? $matches [0] : "";

// clean up globals
return $image;
}
/**
*
*
*/
function renderImage(&$row, $params, $width = 0, $height = 0, $maxchars = 100) {

global $database, $_MAMBOTS, $current_charset;
$image = "";
$regex = "/\<img.+src\s*=\s*\"([^\"]*)\"[^\>]*\>/";
preg_match ( $regex, $row->text, $matches );
$align = ($tmp = $params->get ( "image_alignment", "left" )) != "auto" ? 'align="' . $tmp . '"' : "";
$images = (count ( $matches )) ? $matches : array ();
if (count ( $images ))
$image = $images [1];

if ($image) {
$thumbnailMode = $params->get ( 'thumbnail_mode', 'crop' );
$aspect = $params->get ( 'thumbnail_mode-resize-use_ratio', '1' );
$crop = $thumbnailMode == 'crop' ? true : false;
$olimage = OLImage::getInstance ();

if ($thumbnailMode != 'none' && $olimage->sourceExited ( $image )) {
$imageURL = $olimage->resize ( $image, $width, $height, $crop, $aspect );
if ($imageURL == $image) {
$width = $width ? "width=\"$width\"" : "";
$height = $height ? "height=\"$height\"" : "";
$image = "<img src=\"" . JURI::base () . "$imageURL\" $align  alt=\"{$row->title}\" title=\"{$row->title}\" $width $height />";
} else {
$image = "<img src=\"" . JURI::base () . "$imageURL\"  $align  alt=\"{$row->title}\" title=\"{$row->title}\" />";
}
} else {
$width = $width ? "width=\"$width\"" : "";
$height = $height ? "height=\"$height\"" : "";
$image = "<img src=\"$image\" alt=\"{$row->title}\" $align  title=\"{$row->title}\" $width $height />";
}
} else {
$image = '';
}

$regex1 = "/\<img.*\/\>/";
$row->introtext = preg_replace ( $regex1, '', $row->introtext );
$row->introtext = trim ( $row->introtext );

// clean up globals
return $image;
}
/**
* output html form custom layout which put in the template of configuration.
*/
function outputShowNews(&$row, &$params) {

$mainframe = JFactory::getApplication ();
/*Max chars : number of chars for description*/
$descMaxChars = $params->get("desc_max_chars",100);
$titleMaxChars = $params->get("title_max_chars",30);

$row->text = $row->introtext;
$row->readmore = (trim ( $row->text ) != '') && ($params->get ( 'readmore' ));

$params->set ( 'image', 1 );

$results = $mainframe->triggerEvent ( 'onPrepareContent', array (&$row, &$params, null ), true );
$html = "";
$newTitle = "";
if ($params->get ( 'link_titles' ))
$newTitle .= "<a href=\"" . $this->getLink ( $row ) . "\" title=\"" . $row->title . "\">" . $row->title . "</a>";
else
$newTitle .= "" . $row->title . "";
//Get image
$regex = "/\<img.*\/\>/";
$img = $this->renderImage ( $row, $params, $this->iwidth, $this->iheight );
//preg_match ($regex, $row->text, $matches);
$row->text = preg_replace ( $regex, '', $row->text );
$strTemplate = $params->get ( "templates", '[div style="overflow:hidden; height:323px;" ][div class="snphotos"]##IMAGE##[/div][div class="nftitle"]##TITLE##[/div][div class="nfcontent"]##CONTENT##[/div][/div]' );

$strTemplate = $this->_replaceBBCode ( $strTemplate );
$newReadmore = "<a href=\"" . $this->getLink ( $row ) . "\" title=\"" . $row->title . "\">" . JText::_ ( 'READ_MORE' ) . "</a>";
//$html = str_replace( "##TITLE##",$newTitle, );
$newTitle = $this->trimString( $newTitle, $titleMaxChars );
$html = str_replace ( "##TITLE##", $newTitle, $strTemplate );
$html = str_replace ( "##CONTENT##", $this->trimString($row->text, $descMaxChars) , $html );

//$img  = count($matches) ? $matches[0] : "";
$regex = "/src\=\"images/";
$img = preg_replace ( $regex, 'src="' . JURI::base () . 'images/', $img );
$this->_img [] = $img;
if ($img && ($params->get ( 'link_images', 0 ))) {
$img = "<a href=\"" . $this->getLink ( $row ) . "\" title=\"" . $row->title . "\">" . $img . "</a>";
}
$html = str_replace ( "##IMAGE##", $img, $html );
$html = str_replace ( "##READMORE##", $newReadmore, $html );
$this->_html [] = $html;
return $html;
}
private function _replaceBBCode($strBB = "") {
$strReturn = "";
if (! empty ( $strBB )) {
$arrFind = array ("[", "]" );
$arrReplace = array ("<", ">" );
$strReturn = str_replace ( $arrFind, $arrReplace, $strBB );
}
return $strReturn;
}

function trimString( $title, $maxchars=60  )
{
if (function_exists ( 'mb_substr' )) {
$doc = JDocument::getInstance ();
return SmartTrim::mb_trim ( ($title), 0, $maxchars, $doc->_charset );
} else {
return SmartTrim::trim ( ($title), 0, $maxchars );
}
}
}
?>

<?php
if (! class_exists ( 'SmartTrim' )) {
class SmartTrim {
/*
$hiddenClasses: Class that have property display: none or invisible.
*/
function mb_trim($strin, $pos = 0, $len = 10000, $hiddenClasses = '', $encoding = 'utf-8') {
mb_internal_encoding ( $encoding );
$strout = trim ( $strin );

$pattern = '/(<[^>]*>)/';
$arr = preg_split ( $pattern, $strout, - 1, PREG_SPLIT_DELIM_CAPTURE );
$left = $pos;
$length = $len;
$strout = '';
for($i = 0; $i < count ( $arr ); $i ++) {
$arr [$i] = trim ( $arr [$i] );
if ($arr [$i] == '')
continue;
if ($i % 2 == 0) {
if ($left > 0) {
$t = $arr [$i];
$arr [$i] = mb_substr ( $t, $left );
$left -= (mb_strlen ( $t ) - mb_strlen ( $arr [$i] ));
}

if ($left <= 0) {
if ($length > 0) {
$t = $arr [$i];
$arr [$i] = mb_substr ( $t, 0, $length );
$length -= mb_strlen ( $arr [$i] );
if ($length <= 0) {
$arr [$i] .= '...';
}

} else {
$arr [$i] = '';
}
}
} else {
if (SmartTrim::isHiddenTag ( $arr [$i], $hiddenClasses )) {
if ($endTag = SmartTrim::getCloseTag ( $arr, $i )) {
while ( $i < $endTag )
$strout .= $arr [$i ++] . "\n";
}
}
}
$strout .= $arr [$i] . "\n";
}
//echo $strout;
return SmartTrim::toString ( $arr, $len );
}

function trim($strin, $pos = 0, $len = 10000, $hiddenClasses = '') {
$strout = trim ( $strin );
$pattern = '/(<[^>]*>)/';
$arr = preg_split ( $pattern, $strout, - 1, PREG_SPLIT_DELIM_CAPTURE );
$left = $pos;
$length = $len;
$strout = '';
for($i = 0; $i < count ( $arr ); $i ++) {
$arr [$i] = trim ( $arr [$i] );
if ($arr [$i] == '')
continue;
if ($i % 2 == 0) {
if ($left > 0) {
$t = $arr [$i];
$arr [$i] = substr ( $t, $left );
$left -= (strlen ( $t ) - strlen ( $arr [$i] ));
}

if ($left <= 0) {
if ($length > 0) {
$t = $arr [$i];
$arr [$i] = substr ( $t, 0, $length );

$length -= strlen ( $arr [$i] );
if ($length <= 0) {
$arr [$i] .= '...';
}

} else {
$arr [$i] = '';
}
}
} else {
if (SmartTrim::isHiddenTag ( $arr [$i], $hiddenClasses )) {
if ($endTag = SmartTrim::getCloseTag ( $arr, $i )) {
while ( $i < $endTag )
$strout .= $arr [$i ++] . "\n";
}
}
}
$strout .= $arr [$i] . "\n";
}
//echo $strout;
return SmartTrim::toString ( $arr, $len );
}

function isHiddenTag($tag, $hiddenClasses = '') {
//By pass full tag like img
if (substr ( $tag, - 2 ) == '/>')
return false;
if (in_array ( SmartTrim::getTag ( $tag ), array ('script', 'style' ) ))
return true;
if (preg_match ( '/display\s*:\s*none/', $tag ))
return true;
if ($hiddenClasses && preg_match ( '/class\s*=[\s"\']*(' . $hiddenClasses . ')[\s"\']*/', $tag ))
return true;
}

function getCloseTag($arr, $openidx) {
$tag = trim ( $arr [$openidx] );
if (! $openTag = SmartTrim::getTag ( $tag ))
return 0;

$endTag = "<$openTag>";
$endidx = $openidx + 1;
$i = 1;
while ( $endidx < count ( $arr ) ) {
if (trim ( $arr [$endidx] ) == $endTag)
$i --;
if (SmartTrim::getTag ( $arr [$endidx] ) == $openTag)
$i ++;
if ($i == 0)
return $endidx;
$endidx ++;
}
return 0;
}

function getTag($tag) {
if (preg_match ( '/\A<([^\/>]*)\/>\Z/', trim ( $tag ), $matches ))
return ''; //full tag
if (preg_match ( '/\A<([^ \/>]*)([^>]*)>\Z/', trim ( $tag ), $matches )) {
//echo "[".strtolower($matches[1])."]";
return strtolower ( $matches [1] );
}
//if (preg_match ('/<([^ \/>]*)([^\/>]*)>/', trim($tag), $matches)) return strtolower($matches[1]);
return '';
}

function toString($arr, $len) {
$i = 0;
$stack = new OLStack ( );
$length = 0;
while ( $i < count ( $arr ) ) {
$tag = trim ( $arr [$i ++] );
if ($tag == '')
continue;
if (SmartTrim::isCloseTag ( $tag )) {
if ($ltag = $stack->getLast ()) {
if ('</' . SmartTrim::getTag ( $ltag ) . '>' == $tag)
$stack->pop ();
else
$stack->push ( $tag );
}
} else if (SmartTrim::isOpenTag ( $tag )) {
$stack->push ( $tag );
} else if (SmartTrim::isFullTag ( $tag )) {
//echo "[TAG: $tag, $length, $len]\n";
if ($length < $len)
$stack->push ( $tag );
} else {
$length += strlen ( $tag );
$stack->push ( $tag );
}
}

return $stack->toString ();
}

function isOpenTag($tag) {
if (preg_match ( '/\A<([^\/>]+)\/>\Z/', trim ( $tag ), $matches ))
return false; //full tag
if (preg_match ( '/\A<([^ \/>]+)([^>]*)>\Z/', trim ( $tag ), $matches ))
return true;
return false;
}

function isFullTag($tag) {
//echo "[Check full: $tag]\n";
if (preg_match ( '/\A<([^\/>]*)\/>\Z/', trim ( $tag ), $matches ))
return true; //full tag
return false;
}

function isCloseTag($tag) {
if (preg_match ( '/<\/(.*)>/', $tag ))
return true;
return false;
}
}

class OLStack {
var $_arr = null;
function OLStack() {
$this->_arr = array ();
}

function push($item) {
$this->_arr [count ( $this->_arr )] = $item;
}
function pop() {
if (! $c = count ( $this->_arr ))
return null;
$ret = $this->_arr [$c - 1];
unset ( $this->_arr [$c - 1] );
return $ret;
}
function getLast() {
if (! $c = count ( $this->_arr ))
return null;
return $this->_arr [$c - 1];
}
function toString() {
$output = '';
foreach ( $this->_arr as $item ) {
$output .= $item . "\n";
}
return $output;
}
}
}

?>
